import axios from 'axios'
import router from '@/router';
import store from '@/store'
import { Message } from 'element-ui';

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 100000 * 5
})

// 请求产生的中间件
service.interceptors.request.use((config) => {
  // Do something before request is sent
  const token = store.getters["user/token"]
  Object.assign(config.headers, { Authorization: 'Bearer ' + token })
  return config
}, (error) => {
  // Do something with request error
  return Promise.reject(error)
})

// 响应产生的中间件
service.interceptors.response.use((response) => {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  console.log(response)
  if (response.status != 200) {
    Message.error(response.data.msg)
    return Promise.reject(response);
  }
  if (response.data.code == 40002) {
    // TODO: 等通用提示样式出来了再替换样式
    router.replace({
      name: 'login',
    });
    Message.error('用户认证失败');
    return Promise.reject(response);
  }
  if (response.data.code != 200) {
    Message.error(response.data.msg)
    return Promise.reject(response);
  }
  return Promise.resolve(response);
}, (error) => {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  console.log(error)
  const statusCode = error.response.status
  switch (statusCode) {
    case 401:
      router.replace({
        name: 'login',
      });
      break
    case 403:
      break
    case 404:
      break
    case 500:
      break
    default:
      break
  }
  Message.error(error.response.data.message)
  return Promise.reject(error)
})

export default service
